package com.example.bookstore.config

import com.example.bookstore.config.filter.CorsFilter
import com.example.bookstore.config.filter.GenerateTokenForUserFilter
import com.example.bookstore.config.filter.TokenVerifyFilter
import com.example.bookstore.security.AccessDeniedToJsonHandler
import com.example.bookstore.security.AuthenticationToJsonEntryPoint
import com.example.bookstore.security.MyUserDetailsService
import com.example.bookstore.security.TokenServiceImpl
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.Configuration
import org.springframework.data.redis.core.StringRedisTemplate
import org.springframework.http.HttpMethod
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter
import org.springframework.security.web.access.channel.ChannelProcessingFilter
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter


/**
 * Created by IntelliJ IDEA.
 * User: lvshe
 * Date: 2019/8/13
 * Time: 18:57
 */

@Configuration
class SecurityConfig : WebSecurityConfigurerAdapter() {

    @Autowired
    private lateinit var userDetailsService: MyUserDetailsService
    @Autowired
    private lateinit var tokenService: TokenServiceImpl
    @Autowired
    private lateinit var redisTemplate: StringRedisTemplate


    override fun configure(http: HttpSecurity) {
        http.authorizeRequests()
                .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
//                .antMatchers("/api/session").permitAll()
                .antMatchers("/api/user", "/api/user/**").authenticated()
                .anyRequest().permitAll()
//                .anyRequest().authenticated()
//                .and().headers().cacheControl()

        http.exceptionHandling().accessDeniedHandler(AccessDeniedToJsonHandler()).authenticationEntryPoint(AuthenticationToJsonEntryPoint())
                .and()
                .anonymous().and()
                .csrf().disable()
                .addFilterBefore(CorsFilter(), ChannelProcessingFilter::class.java)
                .addFilterBefore(TokenVerifyFilter(tokenService, userDetailsService), UsernamePasswordAuthenticationFilter::class.java)
                .addFilterBefore(GenerateTokenForUserFilter("/api/session", tokenService, redisTemplate, authenticationManager()), UsernamePasswordAuthenticationFilter::class.java)
    }

}